<?php


namespace common\components\form\field;

use Yii;
use yii\helpers\Html;
use common\components\form\Form;
use common\components\form\Field;
use backend\components\Icon;

/**
 * description of Media
 *
 * @author FireLoong
 */
class Media extends Field
{
    public function setup($options = [])
    {
        if ($this->setupParams) {
            $options = $this->setupParams[0] ?? $options;
        }
        $options = array_merge($this->inputOptions, $options);

        if ($this->form->validationStateOn === Form::VALIDATION_STATE_ON_INPUT) {
            $this->addErrorClassIfNeeded($options);
        }

        $this->addAriaAttributes($options);
        $this->adjustLabelFor($options);
        $input = Html::activeTextInput($this->model, $this->attribute, array_merge($options, ['readonly' => true]));

        $dataContentDefault = Yii::t('common', 'NO_SELECTED_IMAGE');
        $preview = Html::tag('span', Icon::i('eye'), [
            'class' => 'input-group-addon',
            'title' => Yii::t('common', 'SELECTED_IMAGE'),
            'data' => [
                'toggle' => 'popover',
                'trigger' => 'hover',
                'html' => 'true',
                'content' => $dataContentDefault
            ]
        ]);
        $modalId = 'media_modal_' . Html::getInputId($this->model, $this->attribute);
        $selectButton = Html::button(Yii::t('common', 'SELECT'), [
            'class' => 'btn btn-default',
            'data' => [
                'toggle' => 'modal',
                'target' => '#' . $modalId
            ]
        ]);
        $clearButton = Html::button(Yii::t('common', 'CLEAR'), ['class' => 'img-clear btn btn-default']);
        $buttons = Html::tag('div', $selectButton . $clearButton, ['class' => 'input-group-btn']);

        $this->parts['{input}'] = Html::tag('div', $preview . $input . $buttons, ['class' => 'input-group']);

        $view = $this->form->view;

        $inputId = $this->getInputId();

        $view->registerCss('.popover .popover-content img{max-width:200px;max-height:200px;}');
        $iframeSrc = \yii\helpers\Url::to(['/media/images/index']);
        $js = <<<JS
$('#$modalId').on('show.bs.modal', function(e) {
  let iframe = $(e.target).find('iframe').attr('src');
  if (iframe === undefined){
      $(e.target).find('iframe').attr('src', '$iframeSrc');
  }
});
$('#$modalId iframe').load(function() {
  $(this).contents().find('#modal_cancel').click(function() {
    $('#$modalId').modal('hide');
  });
  $(this).contents().find('#modal_insert').click(function() {
    let imgUrl = $('#$modalId iframe').contents().find('#img_url').val();
    $('#$inputId').val(imgUrl);
    $('#$modalId').modal('hide');
  });
});
JS;
        $view->registerJs($js);
        $popoverJs = <<<JS
$('[data-toggle="popover"]').popover();
$('[data-toggle="popover"]').on('show.bs.popover', function() {
  let imgUrl = $(this).find(' + input').val();
  $(this).attr('data-content',imgUrl==='' ? '$dataContentDefault' : '<img src="' + imgUrl + '">');
});
$('.img-clear').click(function() {
  $(this).closest('.form-group').find('input.form-control').val('');
});
JS;
        $view->registerJs($popoverJs);

        $view->on($view::EVENT_END_BODY, function () use ($modalId) {
            $modalTitle = Yii::t('common', 'CHANGE_IMAGE');
            $html = <<<HTML
<div id="$modalId" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">$modalTitle</h4>
            </div>
            <div class="modal-body">
                <div class="embed-responsive embed-responsive-4by3">
                    <iframe class="embed-responsive-item"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>
HTML;
            echo $html;
        });

        return $this;
    }
}
